package com.tudouji.project.bill.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.mchange.v2.uid.UidUtils;
import com.tudouji.common.utils.AccountDate;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.bill.domain.Whinfo;
import com.tudouji.project.bill.domain.Whinforecord;
import com.tudouji.project.bill.mapper.WhinfoMapper;
import com.tudouji.project.bill.mapper.WhinforecordMapper;
import com.tudouji.project.bill.service.IWhinfoService;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.ISalespermissionService;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.service.IStoreroomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 库存信息Service业务层处理
 *
 * @author tudouji
 * @date 2021-04-13
 */
@Slf4j
@Service
public class WhinfoServiceImpl implements IWhinfoService {
    @Autowired
    private WhinfoMapper whinfoMapper;
    @Autowired
    private ISalespermissionService permissionService;
    @Autowired
    private IStoreroomService storeroomService;
    @Autowired
    private WhinforecordMapper whinforecordMapper;

    /**
     * 查询库存信息
     *
     * @param autoid 库存信息ID
     * @return 库存信息
     */
    @Override
    public Whinfo selectWhinfoById(Long autoid) {
        return whinfoMapper.selectWhinfoById(autoid);
    }

    /**
     * 查询库存信息列表
     *
     * @param whinfo 库存信息
     * @return 库存信息
     */
    @Override
    public List<Whinfo> selectWhinfoList(Whinfo whinfo) {
        return whinfoMapper.selectWhinfoList(whinfo);
    }

    /**
     * 新增库存信息
     *
     * @param whinfo 库存信息
     * @return 结果
     */
    @Override
    public int insertWhinfo(Whinfo whinfo) {
        return whinfoMapper.insertWhinfo(whinfo);
    }

    /**
     * 修改库存信息
     *
     * @param whinfo 库存信息
     * @return 结果
     */
    @Override
    public int updateWhinfo(Whinfo whinfo) {
        return whinfoMapper.updateWhinfo(whinfo);
    }

    /**
     * 批量删除库存信息
     *
     * @param autoids 需要删除的库存信息ID
     * @return 结果
     */
    @Override
    public int deleteWhinfoByIds(Long[] autoids) {
        return whinfoMapper.deleteWhinfoByIds(autoids);
    }

    /**
     * 删除库存信息信息
     *
     * @param autoid 库存信息ID
     * @return 结果
     */
    @Override
    public int deleteWhinfoById(Long autoid) {
        return whinfoMapper.deleteWhinfoById(autoid);
    }

    public List<Whinfo> findDetailPC(Whinfo whinfo, String tuserId, boolean isExport) throws Exception {
        // 查询用户是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFunc(tuserId, "10", "4");
        int flag = 0;
        if (permissions.size() < 1) {// 没有全局权限
            // 渠道
            List<Salespermission> srs = permissionService.getPermByScAndFunc(tuserId, "10", "7");
            if (srs.size() > 0) {
                flag = 1;
                String[] srGuids = new String[srs.size()];
                for (int i = 0; i < srs.size(); i++) {
                    srGuids[i] = srs.get(i).getSrguid();
                }
                whinfo.setSrguids(srGuids);
                flag = 1;
            }
        } else {
            flag = 1;
        }
        if (flag == 1) {
            if (!isExport) {
                startPage();
            }
            return whinfoMapper.findDetailPC(whinfo);
        }
        return new ArrayList<Whinfo>();
    }

    @Override
    public Double findStatistics(Whinfo whinfo) {
        return whinfoMapper.findStatistics(whinfo);
    }

    @Override
    public Whinfo getFarmerWhinfo(String productguid, String srguid, String shrguid) {
        Whinfo whinfo = new Whinfo();
        whinfo.setProductid(productguid);
        whinfo.setStorermguid(srguid);
        whinfo.setStorehguid(shrguid);
        return whinfoMapper.getFarmerWhinfo(whinfo);
    }

    @Override
    public Whinfo getWhinfo(String orgguid, String productguid, String srguid, String shrguid, String spguid) {
        Whinfo whinfo = new Whinfo();
        whinfo.setOrgguid(orgguid);
        whinfo.setProductid(productguid);
        whinfo.setStorermguid(srguid);
        whinfo.setStorehguid(shrguid);
        whinfo.setSpguid(spguid);
        return whinfoMapper.getWhinfo(whinfo);
    }

    @Override
    public List<Whinfo> getWhinfos(String orgguid, String srguid, String shrguid, BigDecimal storeqty) {
        Whinfo whinfo = new Whinfo();
        whinfo.setOrgguid(orgguid);
        whinfo.setStorermguid(srguid);
        whinfo.setStorehguid(shrguid);
        whinfo.setStoreqty(storeqty);
        return whinfoMapper.getWhinfos(whinfo);
    }

    @Override
    public AjaxResult getPLInfo(Long strmid, String shrtype, String productid, String spec, String orgid) {
        List<Whinfo> infos = new ArrayList<>();
        Storeroom room = storeroomService.selectStoreroomById(strmid);
        Whinfo info = new Whinfo();
        if (org.apache.commons.lang.StringUtils.isBlank(orgid)) {
            info.setOrgguid(room.getOrgId()+"");
        } else {
            info.setOrgguid(orgid);
        }
        info.setStorermguid(room.getGuid());
        info.setProductid(productid);
        info.setSpguid(spec);
        if (StringUtils.isNotEmpty(shrtype)){
            info.setShrtype(Integer.valueOf(shrtype));
        }
        infos.addAll(whinfoMapper.findstroom(info));
//        if (infos.size() > 0) {
//            for (int i = 0; i < infos.size(); i++) {
//                if (BigDecimal.ZERO.compareTo(infos.get(i).getStoreqty()) == 1 ||
//                        BigDecimal.ZERO.compareTo(infos.get(i).getStoreqty()) == 0) {
//                    infos.remove(infos.get(i));
//                }
//            }
//        }
        return AjaxResult.success(infos);
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void recoverWhinfo(String starttime, String endtime) throws Exception{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //1.日期循环
        List<String> list = AccountDate.getEveryday(starttime, endtime);
        for (String item : list) {
            log.info("==========================="+ item +"==========================");
            Date today = format.parse(item);
            //2.获取前一天whinforecord
            Whinforecord record = new Whinforecord();
            record.setRecorddate(today);
            List<Whinforecord> preRecords = whinforecordMapper.getPreRecord(record);
            //3.删除当天whinforecord
            whinforecordMapper.deleteNowRecord(record);
            //3.插入前一天whinforecord，修改recordtime为当天,并查找出
            for (Whinforecord pre: preRecords){
                if (null != pre){
                    pre.setRecorddate(today);
                    pre.setGuid(IdUtils.fastSimpleUUID());
                    whinforecordMapper.insertWhinforecord(pre);
                }
            }
//				List<Whinforecord> nowRecords = whinforecordDAO.find(record);
            //4.查询当天入库：五项唯一，判断库间类型，gruop by
            List<Whinforecord> whinsY = whinforecordMapper.getNowWhinY(record);
//				List<Whinforecord> whins = whinforecordDAO.getNowWhin(record);
            //5.循环当天入库，判断当天whinforecord是否满足4
            Whinforecord info = new Whinforecord();
            for (int i = 0; i < whinsY.size(); i++) {
                Whinforecord whin = whinsY.get(i);
                if (null != whin) {
						/*if (1 == whin.getShrtype()) {
							info = this.getWhinfoR(whin.getOrgguid(), whin.getProductid(), whin.getStorermguid(),
									whin.getStorehguid(), today);
						} else {*/
                    info = this.getWhinfoR(whin.getOrgguid(), whin.getProductid(), whin.getStorermguid(),
                            whin.getStorehguid(), whin.getSpguid(), today);
//						}
                    if (info != null) {
                        Whinforecord upinfo = new Whinforecord();
                        upinfo.setGuid(info.getGuid());
                        upinfo.setStoreqty((info.getStoreqty() == null ? BigDecimal.ZERO:info.getStoreqty()).add(whin.getStoreqty()));
                        if (info.getStorehguid().equalsIgnoreCase("0A49F17506A045EBBDF0288545E84895")){
                            log.info("IRcome store start:" + info.getStoreqty());
                            log.info("IRcome code:" + whin.getFormno());
                            log.info("IRcome code_weight:" + whin.getStoreqty());
                            log.info("IRcome code_business:" + whin.getBusinessCode());
                            log.info("IRcome store end  :" + upinfo.getStoreqty());
                        }
                        whinforecordMapper.updateWhinforecord(upinfo);
                    }else{
                        log.info("IRcome store start----:" + whin.getStoreqty());
                        log.info("IRcome code:" + whin.getFormno());
                        log.info("IRcome code_weight:" + whin.getStoreqty());
                        log.info("IRcome code_business:" + whin.getBusinessCode());
                        log.info("IRcome store end-----  :" + whin.getStoreqty());
                        whin.setRecorddate(today);
                        whin.setGuid(IdUtils.fastSimpleUUID());
                        whinforecordMapper.insertWhinforecord(whin);
                    }
                }
            }
            //6.再此查找出，查询当天出库：五项唯一，判断库间类型，gruop by
//				nowRecords = whinforecordDAO.find(record);
            List<Whinforecord> whoutsY = whinforecordMapper.getNowWhoutY(record);
//				List<Whinforecord> whouts = whinforecordDAO.getNowWhout(record);
            for (int i = 0; i < whoutsY.size(); i++) {
                Whinforecord whout = whoutsY.get(i);
                if (null != whout) {
						/*if (1 == whout.getShrtype()) {
							info = this.getWhinfoR(whout.getOrgguid(), whout.getProductid(), whout.getStorermguid(),
									whout.getStorehguid(), today);
						} else {*/
                    info = this.getWhinfoR(whout.getOrgguid(), whout.getProductid(), whout.getStorermguid(),
                            whout.getStorehguid(), whout.getSpguid(),today);
//						}
                    if (info != null) {
                        BigDecimal lef = info.getStoreqty();
                        Whinforecord upinfo = new Whinforecord();
                        upinfo.setGuid(info.getGuid());
                        upinfo.setStoreqty((info.getStoreqty() == null ? BigDecimal.ZERO:info.getStoreqty()).subtract(whout.getStoreqty()));
                        if (info.getStorehguid().equalsIgnoreCase("0A49F17506A045EBBDF0288545E84895")){
                            log.info("Qcome store start:" + info.getStoreqty());
                            log.info("Qcome store end  :" + upinfo.getStoreqty());
                        }
                        whinforecordMapper.updateWhinforecord(upinfo);

                    }else{
                        log.info("store can not find：" + JSONUtils.toJSONString(whout));
                    }
                }
            }
            log.info("==========================="+ item +"==========================");
        }
    }

    /**
     * 根据公司id,产品id,仓库id,库房id,规格id查询库存信息
     * @param orgguid
     * @param productid
     * @param roomid
     * @param houseid
     * @param spguid
     * @return
     * @throws Exception
     */
    public Whinforecord getWhinfoR(String orgguid,String productid,String roomid,String houseid,String spguid, Date today) throws Exception{
        Whinforecord info=new Whinforecord();
        info.setOrgguid(orgguid);
        info.setProductid(productid);
        info.setStorermguid(roomid);
        info.setStorehguid(houseid);
        info.setSpguid(spguid);
        info.setRecorddate(today);
        info=whinforecordMapper.selectWhinforecord(info);
        return info;
    }

}
